package com.iwhalecloud.bss.kite.cucc.service.attr;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.CallClientUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;

import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * 序列生成处理器
 * Created by huanghaosheng on 2020/11/14 20:54
 */
public class LocalQuerySeqHelper {

    public static String getSeqBySeqType(Map<String, String> inParam, String sceneInstId,
        CuccContextCustDTO cuccContextCustDTO) {
        cuccContextCustDTO = KiteObjectUtils.isEmpty(cuccContextCustDTO) ?
            new CuccContextCustDTO() :
            cuccContextCustDTO;
        Map<String, Object> inParamMap = new HashMap<>();
        inParamMap.put("SEQ_TYPE", KiteMapUtils.getString(inParam, "SEQ_TYPE"));
        inParamMap.put("PROVINCE_CODE", KiteStringUtils.isNotEmpty(cuccContextCustDTO.getProvinceCode()) ?
            cuccContextCustDTO.getProvinceCode() :
            "");
        inParamMap.put("EPARCHY_CODE",
            KiteStringUtils.isNotEmpty(cuccContextCustDTO.getEparchyCode()) ? cuccContextCustDTO.getEparchyCode() : "");
        inParamMap.put("STAFF_ID", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getUserId()));
        // SERVICE_ID传产品roleId
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        List<KiteProdInst> kiteProdInstList = querySceneInstService.listProdInsts(sceneInstId);
        String roleId = "";
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        InstType rootInstType = sceneInst.getRootInstType();

        // 融合本身没有产品，生成不了业务号码，取成员商品
        String req = "";
        Set<String> roleIds = null;

        if (KiteListUtils.isNotEmpty(kiteProdInstList)) {
            // 云业务生成号码时重新设置roleId
            String newOfferId = KiteMapUtils.getString(inParam, "NEW_OFFER_ID");
            String cateId = KiteMapUtils.getString(inParam, "CATE_ID");
            if (KiteStringUtils.isNotEmpty(newOfferId) && KiteStringUtils.isNotEmpty(cateId)
                && KiteStringUtils.equalsAny(cateId, "2000998", "2100982", "2100983")) {
                List<OfferDetail> details = OfferCache.get(newOfferId).listAccessProdDetail();
                for (OfferDetail detail : details) {
                    for (KiteProdInst kiteProdInst : kiteProdInstList) {
                        kiteProdInst.setRoleId(detail.getRoleId());
                    }
                }
            }
            roleIds = kiteProdInstList.stream()
                .filter(kiteProdInst -> KiteStringUtils.isNotEmpty(kiteProdInst.getRoleId()))
                .map(KiteProdInst::getRoleId).collect(Collectors.toSet());
        }
        if (KiteStringUtils.isNotEmpty(roleId)) {
            req = genAccNum(inParam, cuccContextCustDTO, inParamMap, roleId);
        }
        else if (!KiteObjectUtils.isEmpty(roleIds)) {
            for (String roleCode : roleIds) {
                req = genAccNum(inParam, cuccContextCustDTO, inParamMap, roleCode);
                if (KiteStringUtils.isNotEmpty(req)) {
                    break;
                }
            }
        }
        return req;
    }

    private static String genAccNum(Map<String, String> inParam, CuccContextCustDTO cuccContextCustDTO,
        Map<String, Object> inParamMap, String roleId) {
        inParamMap.put("SERVICE_ID", roleId);
        inParamMap.put("SYS_TYPE", KiteMapUtils.getString(inParam, "SYS_TYPE"));
        inParamMap.put("AREA_CODE",
            KiteStringUtils.isNotEmpty(cuccContextCustDTO.getRegionId()) ? cuccContextCustDTO.getRegionId() : "");
        inParamMap.put("SYS_SOURCE", KiteMapUtils.getString(inParam, "SYS_SOURCE"));
      //tcp_cont
        //国际业务49工号业务号码生成特殊处理
//        LoginInfo loginInfo = ContextUtil.getLoginInfo();
//        String provinceCodeNbr=loginInfo.getUserInfo().getPostProvinceNbr();
//        if(!KiteStringUtils.isEmpty(provinceCodeNbr)&&provinceCodeNbr.startsWith("49")){
//            inParamMap.replace("EPARCHY_CODE","499");
//        }
        Map<String, String> tcpContMap = new HashMap<String, String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        inParamMap.put("TCP_CONT", tcpContMap);

        Map<String, Object> uniBssBody = new HashMap<>();
        uniBssBody.put("REQ", inParamMap);
        Map<String, Object> requestMap = LocalTokenUtil.getParamMap(uniBssBody);
        requestMap.put("OP_CODE", "json_bbssUserCenter_UserSeqService_getAllSeq");
        InfServiceHelper.adaptGray(requestMap, inParamMap);
        String result;
        if (CallClientUtils.callByHttp()) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(requestMap));
        }
        Map<String, Object> goodsMap = JSON.parseObject(result, Map.class);
        Map<String, Object> resultBodyMap = (Map<String, Object>) goodsMap.get("UNI_BSS_BODY");
        String req = "";
        if (KiteMapUtils.isNotEmpty(resultBodyMap)) {
            Map<String, Object> rspMap = (Map<String, Object>) resultBodyMap.get("RSP");
            if (KiteMapUtils.isNotEmpty(rspMap)) {
                req = KiteMapUtils.getString(rspMap, "SEQ_ID");
            }
        }
        return req;
    }

    public static String getSeqBySeqType(Map<String, String> inParam, String sceneInstId, String prodInstId,
        CuccContextCustDTO cuccContextCustDTO) {
        cuccContextCustDTO = KiteObjectUtils.isEmpty(cuccContextCustDTO) ?
            new CuccContextCustDTO() :
            cuccContextCustDTO;
        Map<String, Object> inParamMap = new HashMap<>();
        inParamMap.put("SEQ_TYPE", KiteMapUtils.getString(inParam, "SEQ_TYPE"));
        inParamMap.put("PROVINCE_CODE", KiteStringUtils.isNotEmpty(cuccContextCustDTO.getProvinceCode()) ?
            cuccContextCustDTO.getProvinceCode() :
            "");
        inParamMap.put("EPARCHY_CODE",
            KiteStringUtils.isNotEmpty(cuccContextCustDTO.getEparchyCode()) ? cuccContextCustDTO.getEparchyCode() : "");
        inParamMap.put("STAFF_ID", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getUserId()));
        // SERVICE_ID传产品roleId
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteProdInst kiteProdInst = querySceneInstService.getProdInst(cuccContextCustDTO.getCustId(), prodInstId);
        String roleId = "";
        if (!KiteObjectUtils.isEmpty(kiteProdInst)) {
            roleId = kiteProdInst.getRoleId();
            /*roleId = kiteProdInstList.stream()
                .filter(kiteProdInst -> KiteStringUtils.isNotEmpty(kiteProdInst.getRoleId())).findFirst()
                .map(KiteProdInst::getRoleId).orElse("");*/
        }
        String req = genAccNum(inParam, cuccContextCustDTO, inParamMap, roleId);
        return req;
    }
}
